package common
{
	import domain.Project;
	
	import flash.net.SharedObject;
	
	import mx.collections.ArrayCollection;
	import mx.core.Application;
	import mx.utils.URLUtil;
	
	public class SharedObjectUtil
	{
		private var _so:SharedObject;
		private static var _instance:SharedObjectUtil;
		
		[Bindable] public var projects:ArrayCollection = new ArrayCollection();
		
		public function isInteresting( project:Project ):Boolean {
			return interestingProjects.contains( project.key );
		}
		
		public function SharedObjectUtil() { 
			if( _instance != null ) { 
				throw new Error("Use the getInstance method");
			}
		}
		
		public static function getInstance():SharedObjectUtil { 
			if( _instance == null ) { 
				_instance = new SharedObjectUtil();
			}
			return _instance;
		}
		
		private function isSecure():Boolean { 
			return URLUtil.getProtocol(Application.application.url)=="https";
		}
		private function get so():SharedObject { 
			if( _so == null ) { 
				_so = SharedObject.getLocal("flametreeSO", null, isSecure());
			}
			return _so;
		}
		
		[Bindable] public function get bambooUrl():String { 
			return so.data.bambooUrl; 
		}
		public function set bambooUrl(url:String):void {
			so.data.bambooUrl = url;
		}
		
		[Bindable] public function get username():String { 
			return so.data.username; 
		}
		public function set username(username:String):void {
			so.data.username = username;
		}
		[Bindable] public function get password():String { 
			return so.data.password; 
		}
		public function set password(password:String):void {
			so.data.password = password;
		}
		
		[Bindable] public function get refreshRateInMillis():Number { 
			if( so.data.refreshRate == null ) { 
				return -1;
			}
			return so.data.refreshRate; 
		}
		
		public function set refreshRateInMillis(refreshRate:Number):void {
			so.data.refreshRate = refreshRate;
		}

		[Bindable] public function get popupOnBuildFailure():Boolean { 
			if( so.data.popupOnBuildFailure == null ) { 
				return true;
			}
			return so.data.popupOnBuildFailure; 
		}
		
		public function set popupOnBuildFailure(popupOnBuildFailure:Boolean):void {
			so.data.popupOnBuildFailure = popupOnBuildFailure;
		}
		
		[Bindable("interestingProjectsChanged")]
		public function get interestingProjects():ArrayCollection {
			if( so.data.interestingProjects == null ){
				return new ArrayCollection();
			}
			return so.data.interestingProjects; 
		}
		
		public function set interestingProjects( interestingProjects:ArrayCollection ):void {
			so.data.interestingProjects = interestingProjects;
			dispatchEvent(new Event("interestingProjectsChanged"));
		}

		public function clear():void { 
			so.clear();
		}
	}
}